<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" label-width="150px" label-position="left">
      <box-card class="search-box">
        <div class="search">
          <el-input v-model="queryParams.keywords" placeholder="请输入项目人员姓名/执业单位/注册编号/关键信息"></el-input>
          <el-button type="primary" icon="Search" @click="handleQuery()">
            查询一下
          </el-button>
        </div>
        <el-button link class="show-search" @click="toggleSearch">
          <span class="text">显示筛选</span>
          <svg-icon class-name="arrow-double" icon-class="arrow-double"></svg-icon>
        </el-button>
      </box-card>

      <box-card v-show="showSearch" class="filter-box mt24">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="执业单位" prop="practiceCompany">
              <el-input v-model="queryParams.practiceCompany" placeholder="执业单位" clearable
                style="min-width: 240px; max-width: 320px;" @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册编号/执业印章号" prop="registerCode">
              <el-input v-model="queryParams.registerCode" placeholder="注册编号/执业印章号" clearable
                style="min-width: 240px; max-width: 320px;" @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="证书类型" prop="certificateTypes">
              <div v-for="(type, index) in queryParams.certificateTypes" :key="index">
                <el-cascader v-model="queryParams.certificateTypes[index]" placeholder="注册证书类型"
                  :options="optionsCertificateTypes" :props="cascaderCertificateTypesProps" clearable
                  @clear="removeType(index)" style="min-width: 320px; margin-right: 10px;" />
              </div>
              <el-button :disabled="!canAddType" link type="primary" @click="addType">+ 增加类型</el-button>
              <checkbox-group v-model="queryParams.registerLevelExt" :options="personnelTypeExtList" :multiple="false"
                style="margin-left: 15px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="注册地区" prop="registeredAreaId">
              <el-cascader v-model="queryParams.registeredAreaId" placeholder="注册地区" :options="optionsArea"
                :props="cascaderProps" clearable style="min-width: 320px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目人员职称" prop="professionalTitle">
              <el-input v-model="queryParams.professionalTitle" placeholder="项目人员职称" clearable
                style="min-width: 240px; max-width: 320px;" @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系方式" prop="hasContact">
              <el-radio-group v-model="queryParams.hasContact">
                <el-radio-button v-for="dict in contactList" :key="dict.value" :value="dict.value" size="default"
                  border>
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目人员证书" prop="hasCertificate">
              <el-radio-group v-model="queryParams.hasCertificate">
                <el-radio-button v-for="dict in certificateList" :key="dict.value" :value="dict.value" size="default"
                  border>
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="近期证书变更" prop="certificateMonth">
              <el-select v-model="queryParams.certificateMonth" placeholder="近期证书变更" clearable @change="handleQuery"
                style="min-width: 240px; max-width: 320px;">
                <el-option v-for="dict in certificateMonthList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <!-- <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="项目人员职位" prop="professionalTitle">
              <el-select v-model="queryParams.professionalTitle" placeholder="项目人员职位" clearable @change="handleQuery"
                style="min-width: 240px; max-width: 320px;">
                <el-option v-for="dict in professionalTitleList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目人员业绩" prop="hasMohurdScore">
              <el-select v-model="queryParams.hasMohurdScore" placeholder="项目人员业绩" :empty-values="[null, undefined]"
                :value-on-clear="null" clearable @change="handleQuery" style="min-width: 240px; max-width: 320px;">
                <el-option v-for="dict in mohurdScoreList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="10">
          <el-col :span="24" style="display: flex; justify-content: space-between; align-items: center;">
            <el-button link class="hide-search" @click="toggleSearch">
              <span class="text">隐藏筛选</span><svg-icon class-name="arrow-double" icon-class="arrow-double"></svg-icon>
            </el-button>
            <div>
              <el-button @click="resetQuery">重置</el-button>
              <el-button type="primary" @click="handleQuery">确认</el-button>
            </div>
          </el-col>
        </el-row>
        <el-divider />
        <div class="filter-result">
          <label>已选择：</label>
          <ul class="tag-content">
            <li v-if="isNotEmpty(queryData.keywords)">关键词：{{ queryData.keywords }}</li>
            <li v-if="isNotEmpty(queryData.practiceCompany)">执业单位：{{ queryData.practiceCompany }}</li>
            <li v-if="isNotEmpty(queryData.registerCode)">注册编号/执业印章号：{{ queryData.registerCode }}</li>
            <li v-if="isNotEmpty(queryData.certificateTypes)">证书类型：<span
                v-for="(item, index) in queryData.certificateTypes" :key="index">{{ formatNames(item,
                  optionsCertificateTypes)
                }}</span><span v-if="isNotEmpty(queryData.registerLevelExt)">&nbsp;-&nbsp;</span><tag-view
                :options="personnelTypeExtList" :value="queryData.registerLevelExt" />
            </li>
            <li v-if="isNotEmpty(queryData.registeredAreaId)">注册地区：<span>{{ formatNames(queryData.registeredAreaId,
              optionsArea, 'areaName')
                }}</span></li>
            <li v-if="isNotEmpty(queryData.professionalTitle)">项目人员职称：{{ queryData.professionalTitle }}</li>
            <li v-if="isNotEmpty(queryData.hasContact)">联系方式：<tag-view :options="contactList"
                :value="queryData.hasContact" /></li>
            <li v-if="isNotEmpty(queryData.hasCertificate)">项目人员证书：<tag-view :options="certificateList"
                :value="queryData.hasCertificate" /></li>
            <li v-if="isNotEmpty(queryData.certificateMonth)">近期证书变更：<tag-view :options="certificateMonthList"
                :value="queryData.certificateMonth" /></li>
          </ul>
        </div>
      </box-card>
    </el-form>

    <template v-if="dataList.length > 0">
      <box-card v-for="(item, index) in dataList" :key="index" class="box-result mt24" @click="toDetail(item)">
        <div class="box-result-left">
          <div class="p1"><label>{{ item.realName }}</label> {{ item.sex || '&nbsp;性别:未知' }} {{ item.registeredAreaName
            }}</div>
          <ul class="tag-content tag-content-sm">
            <li>{{ item.professionalTitle }}</li>
          </ul>
          <div class="p2">
            任职单位：<el-link type="primary" :href="item.practiceCompanyMohurdUrl" target="_blank" @click.stop>{{
              item.practiceCompany }}</el-link>
            <span class="ml20">参与项目：</span>{{ item.engineerQty }}
            <span class="ml20">证书数量：</span>{{ item.certificateQty }}
          </div>
        </div>
        <div class="box-result-right">
          <el-link type="primary" href="#">TA可能在{{ item.workCompanyQty || 0 }}家企业中有相关任职经历>></el-link>
          <div class="data">
            <div>
              <div>
                <svg-icon icon-class="icon-follow"></svg-icon>
                <span class="text">关注</span>
              </div>
              <div class="num">{{ item.attentionQty }}</div>
            </div>
            <div>
              <div>
                <svg-icon icon-class="icon-hot"></svg-icon>
                <span class="text">热度</span>
              </div>
              <div class="num">{{ item.hotQty }}</div>
            </div>
          </div>
        </div>
      </box-card>
    </template>
    <div v-else>
      <box-card class="mt24">
        <img image="@/assets/images/icon-nodata.png" />
      </box-card>
    </div>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance()
import { getPersonnelList } from '@/api/personnel'
import { getAreas, getRegisterCertificateTypes } from '@/api/common'
const router = useRouter()

const loading = ref(false)
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  hasCertificate: null, // 是否有证书(不填全部1有0无)
  hasContact: null, // 联系方式(不填全部1有0无)
  hasMohurdScore: null, // 四库一业绩(不填全部1有0无)
  job: null, // 人员职位
  keywords: null, // 关键字
  registerLevelExt: [], // 项目人员类型扩展(1同时具备2任意一个)
  practiceCompany: null, // 执业单位
  professionalTitle: null, // 职称
  registerCode: null, // 注册编号
  registeredAreaId: null, // 注册地区
  certificateMonth: null, // 近期证书变更
  certificateTypes: [[]], // 证书类型
})
const queryData = ref({
  hasCertificate: null, // 是否有证书(不填全部1有0无)
  hasContact: null, // 联系方式(不填全部1有0无)
  hasMohurdScore: null, // 四库一业绩(不填全部1有0无)
  job: null, // 人员职位
  keywords: null, // 关键字
  registerLevelExt: [], // 项目人员类型扩展(1同时具备2任意一个)
  practiceCompany: null, // 执业单位
  professionalTitle: null, // 职称
  registerCode: null, // 注册编号
  registeredAreaId: null, // 注册地区
  certificateMonth: null, // 近期证书变更
  certificateTypes: [[]], // 证书类型
})
const dataList = ref([])
const certificateMonthList = ref([{
  label: '最近一个月',
  value: 0,
}, {
  label: '最近三个月',
  value: 1,
}, {
  label: '最近半年',
  value: 2,
}, {
  label: '最近一年',
  value: 3,
}])
const personnelTypeExtList = ref([{
  label: '同时具备',
  value: 1,
}, {
  label: '任意一个',
  value: 2,
}])
const contactList = ref([{
  label: '不限',
  value: '',
}, {
  label: '有联系方式',
  value: 1,
}, {
  label: '无联系方式',
  value: 0,
}])
const certificateList = ref([{
  label: '不限',
  value: '',
}, {
  label: '有证书',
  value: 1,
}, {
  label: '无证书',
  value: 0,
}])
const mohurdScoreList = ref([{
  label: '不限',
  value: '',
}, {
  label: '有四库业绩',
  value: 1,
}, {
  label: '无中标业绩',
  value: 0,
}])
const showSearch = ref(true)
const optionsCertificateTypes = ref([])
const optionsArea = ref([])

const cascaderProps = {
  value: 'id',
  label: 'areaName',
  expandTrigger: 'hover',
  checkStrictly: true,
}

const cascaderCertificateTypesProps = {
  value: 'id',
  label: 'name',
  expandTrigger: 'hover',
  checkStrictly: true,
}
// 获取列表
function getList() {
  loading.value = true
  getPersonnelList({
    ...queryParams.value,
    registerLevelExt: queryParams.value.registerLevelExt[0],
  }).then(res => {
    console.log('getPersonnelList:', res)
    loading.value = false
    if (res.code === 200) {
      dataList.value = res.data.list
      total.value = res.data.total
    }
  })
}
// 获取地区
function fetchAreas(parentId) {
  getAreas({ parentId }).then(res => {
    console.log('fetchAreas:', res)
    if (res.code === 200) {
      optionsArea.value = res.data
    }
  })
}
// 获取注册类型
function fetchRegisterCertificateTypes(parentId) {
  getRegisterCertificateTypes({ parentId }).then(res => {
    console.log('optionsCertificateTypes:', res)
    if (res.code === 200) {
      optionsCertificateTypes.value = res.data
    }
  })
}
// 隐藏打开搜索条件
function toggleSearch() {
  showSearch.value = !showSearch.value
}
// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1
  queryData.value = queryParams.value
  getList()
}
// 重置
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    hasCertificate: null, // 是否有证书(不填全部1有0无)
    hasContact: null, // 联系方式(不填全部1有0无)
    hasMohurdScore: null, // 四库一业绩(不填全部1有0无)
    job: null, // 人员职位
    keywords: null, // 关键字
    registerLevelExt: [], // 项目人员类型扩展(1同时具备2任意一个)
    practiceCompany: null, // 执业单位
    professionalTitle: null, // 职称
    registerCode: null, // 注册编号
    registeredAreaId: null, // 注册地区
    certificateMonth: null, // 近期证书变更
    certificateTypes: [[]], // 证书类型
  }
  proxy.resetForm("queryRef")
  handleQuery()
  queryData.value = {
    hasCertificate: null, // 是否有证书(不填全部1有0无)
    hasContact: null, // 联系方式(不填全部1有0无)
    hasMohurdScore: null, // 四库一业绩(不填全部1有0无)
    job: null, // 人员职位
    keywords: null, // 关键字
    registerLevelExt: [], // 项目人员类型扩展(1同时具备2任意一个)
    practiceCompany: null, // 执业单位
    professionalTitle: null, // 职称
    registerCode: null, // 注册编号
    registeredAreaId: null, // 注册地区
    certificateMonth: null, // 近期证书变更
    certificateTypes: [[]], // 证书类型
  }
}
// 进入详情
function toDetail(item) {
  console.log('toDetail id:', item.id)
  router.push({
    path: 'project-personnel/project-personnel-detail',
    query: {
      id: item.id
    }
  })
}
// 判断是否为空
function isNotEmpty(value) {
  if (Array.isArray(value)) {
    return value.some(isNotEmpty)
  }
  return value !== undefined && value !== null
}
// 是否可以增加类型
const canAddType = computed(() => {
  const lastType = queryParams.value.certificateTypes[queryParams.value.certificateTypes.length - 1]
  return lastType && lastType.length > 0
})
// 增加类型
function addType() {
  if (canAddType.value) {
    queryParams.value.certificateTypes.push([])
  }
}
// 删除类型
function removeType(index) {
  if (queryParams.value.certificateTypes.length > 1) {
    queryParams.value.certificateTypes.splice(index, 1)
  } else {
    queryParams.value.certificateTypes[0] = []
  }
}
// 递归查找名称
const findNames = (ids, options, label) => {
  const names = []
  let currentOptions = options
  for (const id of ids) {
    console.log('id:', id)
    const found = currentOptions.find(option => option.id === id)
    console.log('found:', found)
    if (found) {
      names.push(found[label])
      currentOptions = found.children || []
    }
  }
  return names
}
// 格式化名称
const formatNames = (ids, options, label = 'name') => {
  console.log('ids:', ids)
  const names = findNames(ids, options, label)
  console.log('names:', names)
  if (names.length <= 0) {
    return ''
  }
  return `[${names.join('/')}]`
}

getList()
fetchAreas(100000)
fetchRegisterCertificateTypes(0)
</script>

<style lang="scss" scoped>
.search-box {
  :deep(.box-card-body) {
    display: flex;
    justify-content: center;
  }
}

.search {
  display: flex;
  flex: 1;
  max-width: 700px;
  min-width: 300px;
  height: 48px;

  .el-input {
    position: relative;
    right: -3px;
    z-index: 2;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #AA261D inset;
    }
  }

  .el-button {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    height: 48px;
    position: relative;
    z-index: 1;
  }
}

.show-search,
.hide-search {
  height: 48px;

  .text {
    color: #646566;
  }

  .arrow-double {
    margin-left: 5px;
  }
}

.show-search {
  margin-left: 50px;
}

.filter-result {
  align-items: center;
  display: flex;

  label {
    color: #333333;
    font-size: 14px;
    font-weight: 400;
    white-space: nowrap;
  }
}

.tag-content {
  display: flex;
  list-style: none;
  margin: 0 0 0 10px;
  padding: 0;
  gap: 8px;
  flex-wrap: wrap;

  li {
    border-radius: 4px;
    background: rgba(255, 238, 237, 0.4);
    color: #aa261d;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 14px;
    padding: 7px 16px 7px 16px;
  }
}

.box-result {
  cursor: pointer;

  :deep(.box-card-body) {
    display: flex;
  }

  .box-result-left {
    flex: 1;
  }

  .box-result-right {
    font-size: 14px;
    display: flex;
    flex-direction: column;

    .link {
      color: #2A82E4;
    }

    .data {
      display: flex;
      margin-top: 18px;

      >div {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;

        >div {
          display: flex;
          align-items: center;
        }
      }

      .svg-icon {
        margin-right: 5px;
      }

      .svg-icon,
      .text {
        color: #808080;
      }

      .num {
        color: #333333;
        font-size: 24px;
        margin-top: 5px;
      }
    }
  }

  .p1 {
    color: #323233;
    font-size: 14px;

    label {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .p2 {
    color: #333;
    font-size: 14px;

    .link {
      color: #2A82E4;
    }

    span {
      color: #808080;
    }
  }

  .tag-content-sm {
    margin-left: 0;
    margin-top: 8px;
    margin-bottom: 8px;

    li {
      padding: 4px 8px 4px 8px;
    }
  }
}
</style>